import {Injectable} from '@angular/core';
import {Setofkey} from '../entity/setofkey.model';

import {Observable} from 'rxjs';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import {AppConfig} from '../config';
import {InterceptorService} from './interceptor/interceptor-service';


@Injectable()
export class SetofkeyService {
  private param = 'dicKeys';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  getSetofkeys(): Promise<Setofkey[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Setofkey[])
      .catch(this.handleError);
  }

  getSetofkeyById(id: number): Promise<Setofkey> {
    const url = `${this.url}/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.data as Setofkey)
      .catch(this.handleError);
  }

  hasSetofkeyByKeyCode(keyCode: string, keyId: number): Observable<boolean> {
    const url = `${this.url}/keyCode/${keyCode}/keyId/${keyId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }

    }).catch(this.handleError);
  }

  create(setofkey: Setofkey): Promise<Setofkey> {
    return this.http
      .post(this.url, JSON.stringify(setofkey))
      .toPromise()
      .then(res => res.data as Setofkey)
      .catch(this.handleError);
  }

  update(setofkey: Setofkey): Promise<Setofkey> {
    const url = `${this.url}`;
    return this.http
      .put(url, JSON.stringify(setofkey))
      .toPromise()
      .then(() => setofkey)
      .catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  batchDelete(keyIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  // search(term: string): Observable<Setofkey[]> {
  //   return this.http
  //     .get(`app/setofkeys/?name=${term}`)
  //     .map(response => response.data as Setofkey[]);
  // }
  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }


}


// WEBPACK FOOTER //
// ./src/app/service/setofkey.service.ts
